package 事务操作;


import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Transaction3 {
    public static void main(String[] args) {
        String fkf = null;
        String skf = null;
        int rmb = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入本次转账金额：");
        rmb = sc.nextInt();
        System.out.println("请输入付款方id：");
        fkf = sc.next();
        System.out.println("请输入收款方id：");
        skf = sc.next();
        System.out.println("正在转账"+rmb+"元");
        String url = "jdbc:mysql://localhost:3306/db_jdbc_demo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "1234";
        Connection conn = null;
        PreparedStatement pstmt = null;
//ResultSet省略，因为update没有结果集
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, pass);
            String sql1 = "update t_account set money = money - ? where id = ?";
            String sql2 = "update t_account set money = money + ? where id = ?";
//开启事务 用conn
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql1);
            pstmt.setInt(1,rmb);
            pstmt.setString(2,fkf);
            int i = pstmt.executeUpdate();

            pstmt = conn.prepareStatement(sql2);
            pstmt.setInt(1,rmb);
            pstmt.setString(2,skf);
            int j = pstmt.executeUpdate();
            if(i+j==2){
                System.out.println("转账成功");
                conn.commit();
            }else{
                System.out.println("转账失败");
            }
        } catch (Exception e) {
            System.out.println("账户出现异常");
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            try {
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
